package com.mju.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mju.controller.common.JsonResult;
import com.mju.dao.FavoritesDao;
import com.mju.feign.clients.ProductClient;
import com.mju.pojo.Favorites;
import com.mju.pojo.Product;
import com.mju.service.IFavoritesService;
import com.mju.service.ex.InsertException;
import com.mju.service.ex.UpdateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class FavoritesServiceImpl implements IFavoritesService {
    @Autowired
    private FavoritesDao favoritesDao;

    @Autowired
    private ProductClient productClient;


    @Override
    public Integer addFavorites(Integer uid, Integer pid) {
        Favorites favorites = new Favorites();
        //根据pid查询商品信息
        JsonResult<Product> data = productClient.getById(pid);
        Product product = data.getData();
        System.out.println("product:" + product);
        //填充favorites对象空白字段
        favorites.setUid(uid);
        favorites.setPid(pid);
        favorites.setImage(product.getImage());
        favorites.setPrice(product.getPrice());
        favorites.setTitle(product.getTitle());
        favorites.setSellPoint(product.getSellPoint());
        favorites.setStatus(1);
        int rows = favoritesDao.insert(favorites);
        if(rows == 0) {
            throw new InsertException("服务器插入异常。");
        }
        //取出fid返回给前端页面，以便在搜索界面取消收藏使用
        return favorites.getFid();
    }

    @Override
    public IPage<Favorites> queryFavorites(Integer uid, Integer currentPage, Integer pageSize, Integer status) {
        IPage page = new Page(currentPage, pageSize);
        // 创建查询构建器，根据uid和status条件来查询
        LambdaQueryWrapper<Favorites> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Favorites::getUid, uid).eq(Favorites::getStatus, status);

        favoritesDao.selectPage(page, lqw);
        return page;
    }

    @Override
    public Integer updateFavoritesStatus(Integer status, Integer fid, Integer uid) {
        int result = favoritesDao.updateFavoritesStatus(status, fid, uid);
        if (result == 0){
            throw new UpdateException("服务器异常，取消收藏失败");
        }
        return result;
    }

    @Override
    public Integer queryFavoriteByUidAndPid(Integer uid, Integer pid, Integer status) {
        Integer result = favoritesDao.queryFavoriteByUidAndPid(uid, pid, status);
        if(Objects.isNull(result)) {
            return 0;
        }else {
            return result;
        }
    }
}
